package com.whh.cos.action;

import com.qcloud.cos.model.ObjectMetadata;
import com.whh.cos.model.ObjectInfo;
import com.whh.cos.service.BucketService;
import com.whh.cos.service.ObjectService;
import com.whh.cos.system.ServiceException;
import com.whh.cos.utils.Converter;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.View;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;

/**
 * @author huahui.wu.
 *         Created on 2018/1/16.
 */
@RestController
@RequestMapping(value = "/object")
public class ObjectAction {
    @Resource
    private ObjectService objectService;
    @Resource
    private BucketService bucketService;

    @RequestMapping(value = "/listBucket")
    public List<ObjectInfo> listBucket(@RequestBody HashMap<String, Object> params) throws ServiceException {
        String bucketName = Converter.getString(params, ("bucketName"));
        String prefix = Converter.getString(params, ("prefix"));
        if (bucketName == null) {
            throw new ServiceException(100101, "bucketName is null");
        }
        if (!bucketService.headBucket(bucketName)) {
            throw new ServiceException(100102, "bucket name is not exist");
        }
        return objectService.listObjects(bucketName, prefix);
    }

    @RequestMapping(value = "/headObject")
    public ObjectMetadata headObject(@RequestBody HashMap<String, Object> params) throws ServiceException {
        String bucketName = Converter.getString(params, ("bucketName"));
        String key = Converter.getString(params, ("key"));
        if (bucketName == null || key == null) {
            throw new ServiceException(100101, "params is null");
        }
        if (!bucketService.headBucket(bucketName)) {
            throw new ServiceException(100102, "bucket name is not exist");
        }
        return objectService.headObject(bucketName, key);
    }



}
